<?php

class RegionController extends BaseController
{
    private $req;
    private $auth;

    public function init()
    {
        $this->req = $this->getRequest();
        if ($this->req->isXMLHttpRequest()) {
            Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
            $layout = Zend_Layout::getMvcInstance();
            if ($layout instanceof Zend_Layout) {
                $layout->disableLayout();
            }
        }
    }

    /**
     * 获取地区信息
     * @author imjcw
     * @date   2016-11-19
     */
    public function getRegionAction()
    {
        $type_arr = array('province', 'city');
        $id = (int)$this->req->getPost('id');
        $type = (string)$this->req->getPost('type');

        if (empty($id)) {
            return Response::Error(0, 'ID不能为空');
        }
        if (empty($type) || !in_array($type, $type_arr)) {
            return Response::Error(0, '类型错误');
        }

        $region_biz = new \Biz\Region();
        $region = array();
        switch ($type) {
            case 'province':
                $city_list = $region_biz->getRegionListByParentId($id);
                if (!is_array($city_list) || empty($city_list)) {
                    return Response::Error(0, '城市ID错误');
                }
                // 区域
                $region_info = reset($city_list);
                $area_list = $region_biz->getRegionListByParentId($region_info['id']);
                if (!is_array($area_list) || empty($area_list)) {
                    $area_list = array();
                    $region['area'] = array();
                }
                foreach ($city_list as $key => $city_info) {
                    $region['city'][$key]['id'] = $city_info['id'];
                    $region['city'][$key]['name'] = $city_info['RegionName'];
                }
                foreach ($area_list as $key => $area_info) {
                    $region['area'][$key]['id'] = $area_info['id'];
                    $region['area'][$key]['name'] = $area_info['RegionName'];
                }
                break;

            case 'city':
                $area_list = $region_biz->getRegionListByParentId($id);
                if (!is_array($area_list) || empty($area_list)) {
                    $area_list = array();
                    $region['area'] = array();
                }
                foreach ($area_list as $key => $area_info) {
                    $region['area'][$key]['id'] = $area_info['id'];
                    $region['area'][$key]['name'] = $area_info['RegionName'];
                }
                break;

            default:
                return Response::Error(0, '类型错误');
                break;
        }

        return Response::Success($region, 'success');
    }
}